﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using log4net;
using System.Configuration;
using LapvComponent;
using LapvBussiness;
using LapvWebComponent;

namespace Lapv.page
{
    public partial class CommentMN : System.Web.UI.Page
    {        
        public string domain =ConfigLapv.Instance.DomainAdmin;        
        private static readonly ILog log = LogManager.GetLogger(typeof(CommentMN).Name);
        int newsid = 0;
        protected void Page_Load(object sender, EventArgs e)
        {

            try
            {
                Session["PageSize"].ToString();
            }
            catch (Exception)
            {
                Session["PageSize"] = 0;
            }          
 
            if (Page.IsPostBack) return;
            


            string urlReturn = this.Request.RawUrl.ToString();
            ProviderAdmin.CheckAuthen(urlReturn, 3);
            if (Request.Params["newsid"] != null)
            {
                int.TryParse(Request.Params["newsid"], out newsid);

                using (lapvwebEntities db = new lapvwebEntities())
                {
                    news n = db.news.Include("news_category").Where(en => en.id == newsid).FirstOrDefault();
                    int cateid = n.news_category.id;
                    BindCate();
                    ddlCate.SelectedValue = cateid.ToString();
                    BindNews(cateid);
                    ddlNews.SelectedValue = newsid.ToString();
                }
               
                loadData();
            }
            bindddlPaged();
           
        }
        void BindCate()
        {
            try
            {
                List<news_category> lst = Provider.GetListNewsCate();
                if (lst != null && lst.Count > 0)
                {
                    ddlCate.DataSource = lst;
                    ddlCate.DataTextField = "name";
                    ddlCate.DataValueField = "id";
                    ddlCate.DataBind();
                    ddlCate.Items.Insert(0, new ListItem("---Chọn loại tin---", "0"));
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + "--" + ex.Source + "--" + ex.InnerException);
                ((Lapv)this.Master).MessageError = "Đã xảy ra lỗi. " + ex.Message;
            }
        }
       public void BindNews(int cateid)
        {
            try
            {
                List<news> lst = null;
                if (cateid > 0)
                {
                    using (lapvwebEntities db = new lapvwebEntities())
                    {
                        lst = db.news.Include("news_category").Where(ec => ec.news_category.id == cateid && ec.status == 1).ToList();
                        if (lst != null && lst.Count > 0)
                        {
                            ddlNews.DataSource = lst;
                            ddlNews.DataTextField = "title";
                            ddlNews.DataValueField = "id";
                            ddlNews.DataBind();
                            ddlNews.Items.Insert(0, new ListItem("Chọn tin tức", "0"));
                        }
                        else
                        {
                            ddlNews.Items.Clear();
                            ddlNews.DataSource = null;
 
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + "--" + ex.Source + "--" + ex.InnerException);
                ((Lapv)this.Master).MessageError = "Đã xảy ra lỗi. " + ex.Message;
            }
        }
    
        private void loadData()
        {
            try
            {
                int from = (pager1.CurrentIndex - 1) * pager1.PageSize;
                int intStatus = -1;
                                
                if (ddlStatus.SelectedValue != null && ddlStatus.SelectedValue != "")
                    intStatus = int.Parse(ddlStatus.SelectedValue);
                if (ddlNews.SelectedValue != null && ddlNews.SelectedValue != "")
                    newsid = int.Parse(ddlNews.SelectedValue);
                List<comment> lstComment = null;
                using (lapvwebEntities db = new lapvwebEntities())
                {
                    lstComment=db.comments.Include("news").ToList();
                    if (newsid > 0)
                        lstComment = lstComment.Where(ec => ec.news.id == newsid).ToList();
                    if (intStatus > -1)
                    {
                        bool statusid = false;
                        if (intStatus == 1)
                            statusid = true;
                        lstComment = lstComment.Where(ec => ec.status == statusid).ToList();
                    }                    
                }                
                pager1.ItemCount = lstComment.Count;
                if (pager1.ItemCount < from)
                {
                    from = 0;
                }
                dtgrid.DataSource = lstComment.Skip(from).Take(pager1.PageSize);
                dtgrid.DataBind();
               
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + "--" + ex.Source + "--" + ex.InnerException);
                ((Lapv)this.Master).MessageError = "Lấy dữ liệu bị lỗi. " + ex.Message;
            }
        }
        protected void ChangeCateSelectIndex(object sender, EventArgs e)
        {
            int cateid = 0;
            if (ddlCate.SelectedValue != null && ddlCate.SelectedValue != "0")
                cateid = int.Parse(ddlCate.SelectedValue);
            if (cateid > 0)
                BindNews(cateid);
        }
        protected void ChangeSelectIndex(object sender, EventArgs e)
        {
            loadData();
        }
        protected void ddlPaged_SelectedIndexChanged(object sender, EventArgs e)
        {
            pager1.PageSize = Convert.ToInt32(ddlPaged.SelectedValue);
            loadData();
        }
        void bindddlPaged()
        {
            ddlPaged.Items.Insert(0, new ListItem("10", "10"));
            ddlPaged.Items.Insert(1, new ListItem("15", "15"));
            ddlPaged.Items.Insert(2, new ListItem("20", "20"));
            ddlPaged.Items.Insert(3, new ListItem("30", "30"));
            ddlPaged.Items.Insert(4, new ListItem("50", "50"));
            pager1.PageSize = 50;
            ddlPaged.SelectedValue = "50";
        }
        public void pager_Command(object sender, CommandEventArgs e)
        {
            int currnetPageIndx = Convert.ToInt32(e.CommandArgument);
            pager1.CurrentIndex = currnetPageIndx;
            loadData();
        }

        public void functionGridNews(object source, DataGridCommandEventArgs evt)
        {
            int commentid = 0;
            switch (evt.CommandName.Trim().ToLower())
            {
                case "edit":
                    try
                    {
                        if (evt.CommandArgument.ToString() != null)
                        {
                            commentid = Convert.ToInt32(evt.CommandArgument);
                            if (commentid > 0)
                            {
                                using (lapvwebEntities db = new lapvwebEntities())
                                {
                                    comment cm = db.comments.Where(ec=>ec.id==commentid && ec.status==false).FirstOrDefault();
                                    if (cm != null)
                                    {
                                        cm.status = true;
                                        db.ApplyCurrentValues(cm.EntityKey.EntitySetName, cm);
                                        db.SaveChanges();

                                    }

                                }
                                loadData();
 
                            }
                        }
                    }
                    catch (Exception)
                    {
                        return;
                    }
                    break;
                
            }
        }
        protected void dtgrid_ItemDataBound(Object sender, DataGridItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.Header)
            {

                comment ns = (comment)e.Item.DataItem;
                if (ns != null)
                {
                    if (ns.status == true)
                    {
                        e.Item.Cells[5].CssClass = "hidden";
                    }
                    


                }

            }


        }
       
     
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            ImageButton imageButton = (ImageButton)sender;
            int id = int.Parse(imageButton.CommandArgument);
            try
            {
                using (lapvwebEntities db = new lapvwebEntities())
                {

                    if (id > 0)
                    {
                        comment obj = db.comments.Where(en => en.id == id).FirstOrDefault();
                        if (obj != null)
                        {
                            db.DeleteObject(obj);
                            db.SaveChanges();
                            loadData();
                            logA("Xóa bình luận thành công. Mã bình luận: " + id, "COMMENT_DELETE");
                            ((Lapv)this.Master).MessageInfomational = "Xóa tin thành công!";                            
                        }
                        else
                        {
                            logA("Xóa bình luận không thành công. Do không tồn tại bình luận mã: " + id, "COMMENT_DELETE");
                            ((Lapv)this.Master).MessageError = "Không tồn tại dữ liệu muốn xóa!";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logA("Xóa bình luận không thành công! Mã bình luận: " + id + ". Do " + ex.Message, "COMMENT_DELETE");
                log.Error(ex.Message + "--" + ex.Source + "--" + ex.InnerException);
                ((Lapv)this.Master).MessageError = "Đã xảy ra lỗi. " + ex.Message;
            }
        }


        private void logA(string msg, string type)
        {
            int uid = 0;
            string uname = string.Empty;
            uid = ProviderAdmin.GetUsserId();
            if (Session["UserName"] != null)
                uname = Session["UserName"].ToString();
            ProviderAdmin.AddLog(uid, uname, msg, string.Empty, type);
        }
        public string getStatus(bool status) {
            if (status == false)
            {
                return "Chưa kiểm duyệt";
            }
            else
            {
                return "Đã kiểm duyệt";
            }
            
        }
    }
}
